/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package NetListener;

import com.sun.org.apache.bcel.internal.generic.INSTANCEOF;
import jWASA.PHR;
import jWASA.Sample;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.lang.ClassNotFoundException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Collection;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author gianmariospacagna
 */
public class NetListener extends Thread {

    Boolean stop;
    Integer port;
    Collection samples;
    Collection patientRecords;
    ServerSocket serverSocket;

    public NetListener(Integer port, Collection samples, Collection patientRecords) throws IOException {

        this.port = port;
        this.samples = samples;
        this.patientRecords = patientRecords;
        stop = false;
        this.serverSocket = new ServerSocket(port);
    }

    @Override
    public void run() {
        while (true) {
            while (!stop) {


                try {
                    System.out.println("Server Listening to the port " + port);
                    Socket socket;
                    socket = serverSocket.accept();
                    System.out.println("Connection accepted from " + socket.getInetAddress().getHostAddress());
                    ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
                    Object obj = ois.readObject();

                    if (obj instanceof Sample) {
                        Sample sample= (Sample)obj;
                        samples.add(sample);
                        System.out.println("New Sample received");
                    } else if (obj instanceof PHR) {


                        patientRecords.add((PHR) obj);
                        System.out.println("New PHR received");
                    } else {
                        System.err.println("NetListener-> Object not recognized: "+obj.toString());
                    }
                } catch (Exception e) {
                    //e.printStackTrace();
                    System.err.println("NetListener-> Error with socket");
                }
            }
        }
    }

    public void safeStop() throws IOException {
        stop = true;
        serverSocket.close();


    }

    public void safeResume() {
        stop = false;

    }
}
